// 全局变量保存异步上传的回调数据（封面图片、PDF信息）
let imgPath, pdfPath, size, time;
let book = {};

// 初始化图书数据
function initBook() {
    book.title = $("#title").val();
    book.author = $("#author").val();
    book.press = $("#press").val();
    book.pressTime = $("#pressTime").val();
    book.themeId = $("#keyword").val();
    book.categoryId = $("#category").val();
    book.description = $("#desc").val();

    book.img = imgPath;
    book.src = pdfPath;
    book.size = size;
    book.uploadTime = time;
}

// 修改电子书
$("#modifyBtn").click(function () {

    initBook();
    book.id = $("#bookId").val();

    console.log("修改的图书信息：" + JSON.stringify(book));

    // 提交修改
    $.ajax({
        url: '/api/editBook',
        type: 'post',
        dataType: 'json',
        data: JSON.stringify(book),
        contentType: 'application/json;charset=UTF-8',
        success: function (res) {
            if (res.code === 0) {
                setTimeout(function () {
                    window.open("/admin/bookList", "main");
                }, 800);
            } else {
                layer.msg("修改记录出错，请稍后重试……", {icon:5, anim: 6});
            }
        },
        error: function () {
            layer.msg("服务器出现未知错误……", {icon:5, anim: 6});
        }
    })



});

// 单击提交按钮
$("#submitBtn").click(function () {

    initBook();

    console.log("添加的图书信息：" + JSON.stringify(book));

    /**
     * 2021-02-18 修改
     * 考虑多本上传，只要求书名必填，其它字段可后面添加（修改）
     */
    if (book.title === "" || book.title == null) {
        layer.msg("请输入书名！", {icon: 5, anim: 6});
        return;
    }
    //
    // if (book.author === "" || book.author == null) {
    //     layer.msg("请输入作者！", {icon: 5, anim: 6});
    //     return;
    // }
    //
    // if (book.pressTime === "" || book.pressTime == null) {
    //     layer.msg("请选择出版时间！", {icon: 5, anim: 6});
    //     return;
    // }
    //
    // if (book.categoryId === "" || book.categoryId == null) {
    //     layer.msg("请选择类型！", {icon: 5, anim: 6});
    //     return;
    // }
    //
    // if (book.description === "" || book.description == null) {
    //     layer.msg("请输入图书内容简介！", {icon: 5, anim: 6});
    //     return;
    // }
    //
    // if (book.src === "" || book.src == null) {
    //     layer.msg("请上传电子书PDF！", {icon: 5, anim: 6});
    //     return;
    // }

    // 上传数据
    $.ajax({
        url: '/api/addBook',
        type: 'post',
        dataType: 'json',
        data: JSON.stringify(book),
        contentType: 'application/json;charset=UTF-8',
        success: function (res) {
            if (res.code === 0) {
                // layer.msg("添加图书成功，页面即将跳转……", {icon: 6, anim: 5});
                setTimeout(function () {
                    window.open("/admin/bookList", "main");
                    // window.parent.location.href = "/admin";
                }, 1000);
            } else {
                layer.msg("添加图书失败，请稍后重试……", {icon:5, anim: 6});
            }
        },
        error: function () {
            layer.msg("服务器出现未知错误……", {icon:5, anim: 6});
        }
    })
});

// 重置按钮，与表单结合，此处手动清理img预览图，但是重新上传同一幅会出现不显示，可能是layui的原因
$("#resetBtn").click(function () {
    $("#img").attr("src", "");
});

layui.use(['laydate', 'form', 'element', 'upload'], function () {
    let laydate = layui.laydate;
    let form = layui.form;
    let element = layui.element;
    let upload = layui.upload;

    //执行一个laydate实例
    laydate.render({
        elem: '#pressTime' //指定元素
        , type: 'month'   // 年月选择
    });

    // 封面图片上传
    var uploadInst = upload.render({
        elem: '#uploadImg'
        , url: '/book/upload/img' //改成您自己的上传接口
        , size: 4096    // 最大4MB
        , exts: 'jpg|png|gif|bmp|jpeg'
        , before: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                $('#img').attr('src', result); //图片链接（base64）
            });
        }
        , done: function (res) {
            //如果上传失败
            if (res.code > 0) {
                return layer.msg('上传失败');
            }
            //上传成功
            imgPath = res.dir;
            layer.msg("上传图书封面成功");
        }
        , error: function () {
            //演示失败状态，并实现重传
            var demoText = $('#demoText');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function () {
                uploadInst.upload();
            });
            console.log("上传图片error");
        }
    });

    // 电子书PDF上传
    var uploadInst = upload.render({
        elem: '#uploadPdf'
        , url: '/book/upload/pdf' //改成您自己的上传接口
        , size: 307200    // 最大300MB
        , exts: 'pdf'
        , done: function (res) {
            //如果上传失败
            if (res.code > 0) {
                return layer.msg('PDF上传失败');
            }
            //上传成功
            pdfPath = res.dir;
            size = res.size;
            time = res.time;
            layer.msg("上传图书PDF成功");
        }
        , error: function () {
            //演示失败状态，并实现重传
            var demoText = $('#demoText');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function () {
                uploadInst.upload();
            });
            console.log("上传文件error");
        }
    });
});
